package com.atguigu.gmall.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.app.BaseAppV2;
import com.atguigu.gmall.bean.VisitorStats;
import com.atguigu.gmall.common.Constant;
import com.atguigu.gmall.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Map;

import static com.atguigu.gmall.common.Constant.*;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/4 14:08
 */
public class DwsVisitorStatsApp extends BaseAppV2 {
    public static void main(String[] args) {
        new DwsVisitorStatsApp().init(
            4001,
            1,
            "DwsVisitorStatsApp",
            "DwsVisitorStatsApp",
            TOPIC_DWD_PAGE, TOPIC_DWM_UV, TOPIC_DWM_USER_JUMP_DETAIL);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> streams) {
        // 1. 解析流, 并按照统一的格式union在一起
        DataStream<VisitorStats> visitorStatsStream = parseAndUnion(streams);
        // 2. 开窗聚合
        SingleOutputStreamOperator<VisitorStats> aggregatedStream = aggWithWindow(visitorStatsStream);
        // 3. 写入到ClickHouse中
        writeToClickHouse(aggregatedStream);
        
    
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<VisitorStats> stream) {
        // 自定义ck sink
        stream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB, Constant.TABLE_VISITOR_STATS, VisitorStats.class));
    }
    
    private SingleOutputStreamOperator<VisitorStats> aggWithWindow(DataStream<VisitorStats> visitorStatsStream) {
       return visitorStatsStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(10))
                    .withTimestampAssigner((vs, ts) -> vs.getTs())
            )
            .keyBy(vs -> vs.getVc() + "_" + vs.getCh() + "_" + vs.getAr() + "_" + vs.getIs_new())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .sideOutputLateData(new OutputTag<VisitorStats>("late"){})
            .reduce(
                new ReduceFunction<VisitorStats>() {
                    @Override
                    public VisitorStats reduce(VisitorStats vs1,
                                               VisitorStats vs2) throws Exception {
                        vs1.setUv_ct(vs1.getUv_ct() + vs2.getUv_ct());
                        vs1.setUj_ct(vs1.getUj_ct() + vs2.getUj_ct());
                        vs1.setPv_ct(vs1.getPv_ct() + vs2.getPv_ct());
                        vs1.setSv_ct(vs1.getSv_ct() + vs2.getSv_ct());
                        vs1.setDur_sum(vs1.getDur_sum() + vs2.getDur_sum());
                        
                        return vs1;
                    }
                },
                new ProcessWindowFunction<VisitorStats, VisitorStats, String, TimeWindow>() {
    
                    private SimpleDateFormat sdf;
    
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
    
                    @Override
                    public void process(String s,
                                        Context ctx,
                                        Iterable<VisitorStats> elements,
                                        Collector<VisitorStats> out) throws Exception {
                        // 年月日时分秒
    
                        TimeWindow w = ctx.window();
                        String stt = sdf.format(w.getStart());
                        String edt = sdf.format(w.getEnd());
    
                        VisitorStats vs = elements.iterator().next();
                        vs.setStt(stt);
                        vs.setEdt(edt);
    
                        out.collect(vs);
                        
                    }
                }
            );
    }
    
    private DataStream<VisitorStats> parseAndUnion(Map<String, DataStreamSource<String>> streams) {
        DataStreamSource<String> pageStream = streams.get(TOPIC_DWD_PAGE);
        DataStreamSource<String> uvStream = streams.get(TOPIC_DWM_UV);
        DataStreamSource<String> userJumpStream = streams.get(TOPIC_DWM_USER_JUMP_DETAIL);
        
        // 1. 计算pv 和持续访问市场
        SingleOutputStreamOperator<VisitorStats> pvAndDuringTimeStatsStream = pageStream
            .map(s -> {
                JSONObject obj = JSON.parseObject(s);
                
                JSONObject common = obj.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                JSONObject page = obj.getJSONObject("page");
                Long during_time = page.getLong("during_time");
                
                Long ts = obj.getLong("ts");
                
                VisitorStats vs = new VisitorStats(
                    "", "",
                    vc, ch, ar, is_new,
                    0L, 1L, 0L, 0L, during_time,
                    ts
                );
                return vs;
            });
        
        // 2. 计算uv
        SingleOutputStreamOperator<VisitorStats> uvStatsStream = uvStream
            .map(s -> {
                
                JSONObject obj = JSON.parseObject(s);
                JSONObject common = obj.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                Long ts = obj.getLong("ts");
                
                VisitorStats vs = new VisitorStats(
                    "", "",
                    vc, ch, ar, is_new,
                    1L, 0L, 0L, 0L, 0L,
                    ts
                );
                return vs;
            });
        
        // 3. 计算跳出次数
        SingleOutputStreamOperator<VisitorStats> ujStatsStream = userJumpStream
            .map(s -> {
                JSONObject obj = JSON.parseObject(s);
                JSONObject common = obj.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                Long ts = obj.getLong("ts");
                
                VisitorStats vs = new VisitorStats(
                    "", "",
                    vc, ch, ar, is_new,
                    0L, 0L, 0L, 1L, 0L,
                    ts
                );
                return vs;
            });
        
        // 4. 计算 sv 进入  从哪个数据源?
        SingleOutputStreamOperator<VisitorStats> svStatsStream = pageStream
            .flatMap(new FlatMapFunction<String, VisitorStats>() {
                @Override
                public void flatMap(String s,
                                    Collector<VisitorStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(s);
                    
                    String lastPageId = obj.getJSONObject("page").getString("last_page_id");
                    
                    if (lastPageId == null || lastPageId.length() == 0) {
                        
                        JSONObject common = obj.getJSONObject("common");
                        String vc = common.getString("vc");
                        String ch = common.getString("ch");
                        String ar = common.getString("ar");
                        String is_new = common.getString("is_new");
                        
                        Long ts = obj.getLong("ts");
                        VisitorStats vs = new VisitorStats(
                            "", "",
                            vc, ch, ar, is_new,
                            0L, 0L, 1L, 0L, 0L,
                            ts
                        );
                        out.collect(vs);
                    }
                }
            });
        
        return pvAndDuringTimeStatsStream.union(uvStatsStream, ujStatsStream, svStatsStream);
        
    }
}
